//article.js
//获取应用实例
const app = getApp()
var util= require("../../utils/libs.js")
var api = require("../../utils/api.js")
var WxParse = require('../../wxParse/wxParse.js');
Page({
  data: {
    id: null,
    show:true,
    isStar:true,
    param:'',
    detail: {},
    isSave:true,
    article_content: "",
    uid:null,
    saveText:"收藏",
    shareImage:'',
    user:'',
    description:'',
    title:''
  },
  commit:function(event){
    let that = this;
    let id = event.currentTarget.dataset.id
    if(that.param==""){
      wx.navigateTo({
        url: '../commit/commit?id='+id,
      })
    }else{
      wx.navigateTo({
        url: '../commit/commit?id=' + id+'&param='+that.param,
      })
    }
  },
  handleClick(){
   let that = this
   that.setData({
     show:false
   })
  },
  showDetail(){
    let that = this
    util.request(api.SkillDetail,{id:that.data.id},"GET")
    .then(function (res) {
      if(res.error_code === 0){
        let arr = res.data.article
        console.log(res)
        // arr.create_time = date(arr.create_time)
        var content = res.data.article.content;
        
        //转化文章内容
         WxParse.wxParse('content', 'html', content, that, 0);

         // 获取文章内容
         var s = '';
         var s2 = that.getContent(s);
         var str = s2.substring(0, 30)
         that.setData({
           detail: arr,
           user: arr.author,
           description:str,
           title:arr.title
         })
      }
    })
  },
  getContent(s){
    //获取文章内容节点
    var nodes = wx.getStorageSync('htmldata');
    var arr = nodes.nodes;
    console.log(arr);
    for (var i = 0; i < arr.length; i++) {
      var arr2 = arr[i].nodes;
      //console.log(arr2);
      for (var j = 0; j < arr2.length; j++) {
        var arr3 = arr2[j].nodes
        if (arr3 != undefined) {
          for (var l = 0; l < arr3.length; l++) {
            var arr4 = arr3[l].nodes;
            if (arr4 != undefined) {
              for (var m = 0; m < arr4.length; m++) {
                s += arr4[m].text;
              }
            }
          }
        }
      }
    }
    return s 
  },
  showParam() {
    let that = this
    let uid = wx.getStorageSync('uid');
    util.request(api.recommendA, { id: that.data.id,uid: uid}, "GET")
      .then(function (res) {
        if (res.error_code === 0) {
          let arr = res.data.article
          console.log(res)
          // arr.create_time = date(arr.create_time)
          var content = res.data.article.content;
          that.setData({
            detail: arr,
            user: arr.author,
            description: content.substring(0, 30),
            title: arr.title
          })
          var content = res.data.article.content;
          WxParse.wxParse('content', 'html', content, that, 0);
          // 获取文章内容
          var s = '';
          var s2 = that.getContent(s);
          var str = s2.substring(0, 30)
          that.setData({
            detail: arr,
            user: arr.author,
            description: str,
            title: arr.title
          })
        }
      })
  },
  tothink(){
    let that = this
     if(that.data.isStar){
       let apis;
       if (that.param != '') {
         apis = api.rdoLike
       } else {
         apis = topicDoLike;
       }

      util.request(apis,{id:that.data.id,
        uid:that.data.uid
        },"POST")
        .then(function (res) {
          if(res.error_code === 0){
            wx.showToast({
              title: '点赞成功',
              icon: 'success',
              duration: 2000
            })
            that.setData({
              isStar:false
            })
          }
        })
     }else{
       let apis;
       if (that.param != '') {
         apis = api.cdoLike
       } else {
       let  apis = topiccancelLike;
       }

      util.request(apis,
        {id:that.data.id,
        uid:that.data.uid
        },"POST")
        .then(function (res) {
          if(res.error_code === 0){
            wx.showToast({
              title: '取消点赞',
              icon: 'success',
              duration: 2000
            })
            that.setData({
              isStar:false
            })
          }
        })
     }
   
  },
  closeImg() {
    this.setData({
      shareI:false
    })
  },
  saveI(event){
    var url = event.currentTarget.dataset.src
    console.log(url)
    wx.getSetting({
      success(res) {
        console.log(res)
        if (!res.authSetting['scope.writePhotosAlbum']) {
          wx.authorize({
            scope: 'scope.writePhotosAlbum',
            success() {
              wx.downloadFile({
                url: url,
                success(res){
                  console.log(res)
                  wx.saveImageToPhotosAlbum({
                    filePath: res.tempFilePath,
                    success(res) {
                      console.log(res)
                      wx.showToast({
                        title: '保存成功',
                        icon:'none',
                        duration:2000
                      })
                      that.setData({
                        shareI: false
                      })
                    },
                    fail(res) {
                      console.log(res)
                    }
                  })
                }
              })
            }
          })
        }else{
          wx.downloadFile({
            url: url,
            success(res) {
              console.log(res)
              wx.saveImageToPhotosAlbum({
                filePath: res.tempFilePath,
                success(res) {
                  console.log(res)
                  wx.showToast({
                    title: '保存成功',
                    icon: 'none',
                    duration: 2000
                  })
                  that.setData({
                    shareI: false
                  })
                },
                fail(res) {
                  console.log(res)
                }
              })
            }
          })
        }
      },
      error(res){
        console.log(res)
      }
    })
  },
  share() {
    this.setData({
      shareI: true
    })
  },
  getShare() {
    var that = this
    wx.request({
      // 获取token
      url: 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential',
      data: {
        appid: 'wxb78b3211945cae67',
        secret: 'ad9e02f1ea741473fa5615787c0e9d7e'
      },
      success(res) {
        wx.request({
          // 调用接口C
          url: 'https://api.weixin.qq.com/wxa/getwxacode?access_token=' + res.data.access_token,
          method: 'POST',
          data: {
            path: "pages/index/index",
            width: 430,
            auto_color: false,
            line_color: { r: 0, g: 0, b: 0 }
          },
          success(res) {
            let author = ''
            // res是二进制流，后台获取后，直接保存为图片，然后将图片返回给前台
            // 后台二进制怎么转图片？我也不会后台，学会了再贴代码
            if (that.data.user ==null) {
              author = '未知'
            } else {
              author = that.data.user
            }
            util.request(api.upload, {
              type: 1,
              title: that.data.title,
              author: author,
              description: that.data.description
            }, 'POST').then(function (res) {
              that.setData({
                shareImage: res.data.file
              })
            })


          }
        })
      }


    })
  },
 date(date) {
    var now = new Date(date*1000);
    var year = now.getFullYear();
    var month = (now.getMonth() + 1) < 10 ? '0' + (now.getMonth() + 1) : (now.getMonth() + 1);
    var date = now.getDate();   
    return  year+"-"+month+"-"+date;
  }, 
  toSave(){
    let that = this
    if(that.data.isSave){
      let apis;
      if (that.param != '') {
        apis = api.doStar
      } else {
        let apis = topicdoStar;
      }
      util.request(apis,
        {id:that.data.id,
        uid:that.data.uid
      },"POST")
      .then(function (res) {
        if(res.error_code === 0){
            that.setData({
              isSave:false,
              saveText:"取消收藏"
            })
        }
      })
    }else{
      let apis;
      if (that.param != '') {
        apis = api.cancelStar
      } else {
        let apis = topiccancelStar;
      }
      util.request(apis,
        {id:that.data.id,
        uid:that.data.uid
      },"POST")
      .then(function (res) {
        if(res.error_code === 0){
            that.setData({
              isSave:true,
              saveText:"收藏"
            })
        }
      })
    }
  },
  onLoad(options){
    let that = this
    let uid = wx.getStorageSync('uid')
    that.setData({
      id: options.id,
      uid:uid 
    })

    let param = options.param
    console.log(param)
    if (param == '' || param == undefined) {
      that.param = param
      that.showDetail()
       that.getShare()
    }else{
      that.showParam()
      that.getShare()
    }
  }
})
